import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : 'http://localhost:8083/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    console.log('🔍 API响应拦截器 - 原始响应:', response)
    console.log('🔍 API响应拦截器 - response.data:', response.data)
    
    // 对于Spring Boot后端，直接返回原始响应
    return response
  },
  (error) => {
    console.error('响应错误:', error);
    console.error('响应错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    });
    
    if (error.response) {
      const { status, data } = error.response;
      let message = '请求失败';
      
      switch (status) {
        case 400:
          message = data.message || '请求参数错误';
          break;
        case 401:
          message = '登录已过期，请重新登录';
          console.log('⚠️ 检测到401错误，准备清除认证状态');
          const userStore = useUserStore();
          console.log('清除前状态:', {
            isAuthenticated: userStore.isAuthenticated,
            isLoggedIn: userStore.isLoggedIn,
            hasToken: !!userStore.token,
            tokenLength: userStore.token?.length,
            currentUrl: window.location.pathname
          });
          
          // 只有在用户确实已登录的情况下才清除状态
          if (userStore.isAuthenticated && userStore.isLoggedIn && userStore.token) {
            console.log('用户已登录但收到401，可能是token过期');
          userStore.logout();
          console.log('清除后状态:', {
            isAuthenticated: userStore.isAuthenticated,
            isLoggedIn: userStore.isLoggedIn,
            hasToken: !!userStore.token
          });
            // 使用router.push而不是window.location.href，保持SPA体验
            setTimeout(() => {
          window.location.href = '/login';
            }, 100);
          } else {
            console.log('用户未登录或token无效，不执行跳转');
            // 如果用户未登录，可能是直接访问需要认证的页面
            // 这种情况下不显示错误消息，让路由守卫处理
            return Promise.reject(error);
          }
          break;
        case 403:
          message = '权限不足，无法访问此资源';
          console.log('⚠️ 检测到403错误，但不清除认证状态');
          break;
        case 404:
          message = '请求的资源不存在';
          break;
        case 500:
          message = '服务器内部错误';
          break;
        default:
          message = data.message || '网络错误';
      }
      
      ElMessage.error(message);
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络');
    } else {
      ElMessage.error('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

// 认证相关API
export const authApi = {
  // 登录 - 对接Spring Boot的/api/auth/login
  login: (data) => {
    let loginData = {
      username: data.username,
      password: data.password
    };
    // 如果输入的是手机号，自动加上mobile字段
    if (/^1[3-9]\d{9}$/.test(data.username)) {
      loginData = {
        username: data.username,
        mobile: data.username,
        password: data.password
      };
    }
    return request.post('/auth/login', loginData);
  },
  
  // 注册 - 对接Spring Boot的/api/auth/register
  register: (data) => {
    const registerData = {
      username: data.username,
      email: data.email,
      password: data.password,
      mobile: data.mobile || data.phone
    };
    return request.post('/auth/register', registerData);
  },
  
  // 登出
  logout: () => {
    return Promise.resolve({ data: { message: 'Logged out successfully' } });
  },
  
  // 获取用户信息 - 对接Spring Boot的/api/auth/me
  getUserInfo: () => {
    return request.get('/auth/me')
  },
  
  // 检查用户名可用性
  checkUsernameAvailable: (username) => {
    return request.get(`/auth/check-username?username=${username}`);
  },

  // 发送短信验证码 (注册用)
  sendSmsCode: (phone, type = 'register') => {
    return request.post('/auth/sms-code', { phone, type });
  },

  // 验证码登录
  loginWithCode: (data) => {
    return request.post('/auth/login-code', data);
  },

  // 重置密码
  resetPassword: (data) => {
    return request.post('/auth/reset-password', data);
  },

  // 验证重置密码验证码
  verifyResetCode: (data) => {
    return request.post('/auth/verify-reset-code', data);
  }
};

// 洗护订单相关API - 对接Spring Boot的/api/laundry
export const orderApi = {
  // 创建订单 - 对接/api/laundry/orders
  createOrder: (data) => {
    // 转换前端订单数据到后端格式
    const orderData = {
      customerName: data.customerName,
      customerPhone: data.customerPhone,
      pickupAddress: data.pickupAddress,
      deliveryAddress: data.deliveryAddress,
      totalAmount: data.totalAmount,
      items: data.items || [],
      status: data.status || 'PENDING'
    };
    return request.post('/laundry/orders', orderData);
  },
  
  // 获取订单列表 - 对接/api/laundry/orders
  getOrderList: (params) => {
    // 处理查询参数
    return request.get('/laundry/orders', { params });
  },
  
  // 获取订单列表 - 兼容getOrders调用
  getOrders: (params) => {
    // 处理查询参数
    return request.get('/laundry/orders', { params });
  },
  
  // 获取订单详情 - 对接/api/laundry/orders/{id}
  getOrderDetail: (id) => request.get(`/laundry/orders/${id}`),
  
  // 更新订单 - 对接/api/laundry/orders/{id}
  updateOrder: (id, data) => {
    return request.put(`/laundry/orders/${id}`, data);
  },
  
  // 取消订单
  cancelOrder: (id, reason) => {
    // 通过更新订单状态来取消
    return request.put(`/laundry/orders/${id}`, { 
      status: 'CANCELLED',
      cancelReason: reason 
    });
  },
  
  // 确认订单
  confirmOrder: (id) => {
    return request.put(`/laundry/orders/${id}`, { status: 'CONFIRMED' });
  },
  
  // 删除订单 - 对接/api/laundry/orders/{id}
  deleteOrder: (id) => request.delete(`/laundry/orders/${id}`),
  
  // 评价订单 - 可能需要额外的后端端点
  rateOrder: (id, data) => {
    return request.post(`/laundry/orders/${id}/rating`, data);
  },
  
  // 获取订单进度 - 可能需要额外的后端端点
  getOrderProgress: (id) => {
    return request.get(`/laundry/orders/${id}/progress`);
  },
  
  // 获取订单统计 - 可能需要额外的后端端点
  getOrderStats: () => {
    return request.get('/laundry/orders/stats');
  },
  
  // 重新下单
  reorder: (id) => {
    return request.post(`/laundry/orders/${id}/reorder`);
  }
};

// 商家管理API - 对接Spring Boot的/api/merchants
export const merchantApi = {
  // 获取商家列表 - 对接/api/merchants
  getMerchantList: (params) => request.get('/merchants', { params }),

  // 获取商家详情 - 对接/api/merchants/{id}
  getMerchantDetail: (id) => request.get(`/merchants/${id}`),

  // 获取商家服务 - 对接/api/merchants/{id}/services
  getMerchantServices: (id, params) => request.get(`/merchants/${id}/services`, { params }),

  // 获取高评分商家 - 对接/api/merchants/top-rated
  getTopRatedMerchants: (params) => request.get('/merchants/top-rated', { params }),

  // 获取热门商家 - 对接/api/merchants/popular
  getPopularMerchants: (params) => request.get('/merchants/popular', { params })
};

// 服务管理API - 对接Spring Boot的/api/services
export const serviceApi = {
  // 获取服务分类 - 对接/api/services/categories
  getServiceCategories: () => request.get('/services/categories'),

  // 获取服务列表 - 对接/api/services
  getServiceList: (params) => request.get('/services', { params }),

  // 获取服务详情 - 对接/api/services/{id}
  getServiceDetail: (id) => request.get(`/services/${id}`),

  // 获取推荐服务 - 对接/api/services/recommended
  getRecommendedServices: (params) => request.get('/services/recommended', { params }),

  // 获取热门服务 - 对接/api/services/hot
  getHotServices: (params) => request.get('/services/hot', { params }),

  // 搜索服务 - 对接/api/services/search
  searchServices: (params) => request.get('/services/search', { params })
};

// 搜索功能API - 对接Spring Boot的/api/search
export const searchApi = {
  // 综合搜索 - 对接/api/search
  search: (params) => request.get('/search', { params }),

  // 搜索服务 - 对接/api/search/services
  searchServices: (params) => request.get('/search/services', { params }),

  // 搜索商家 - 对接/api/search/merchants
  searchMerchants: (params) => request.get('/search/merchants', { params }),

  // 获取推荐内容 - 对接/api/search/recommendations
  getRecommendations: () => request.get('/search/recommendations')
};

// 仪表板API - 对接Spring Boot的/api/dashboard
export const dashboardApi = {
  // 获取用户仪表板 - 对接/api/dashboard
  getUserDashboard: () => request.get('/dashboard'),

  // 获取订单统计 - 对接/api/dashboard/orders/stats
  getOrderStats: () => request.get('/dashboard/orders/stats')
};

// 用户管理API - 对接Spring Boot的/api/user
export const userApi = {
  // 获取用户资料 - 对接/api/user/profile
  getUserProfile: () => request.get('/user/profile'),

  // 更新用户资料 - 对接/api/user/profile
  updateUserProfile: (data) => request.put('/user/profile', data),

  // 修改密码 - 对接/api/user/change-password
  changePassword: (data) => request.put('/user/change-password', data),

  // 更新手机号 - 对接/api/user/mobile
  updateMobile: (data) => request.put('/user/mobile', data),

  // 更新邮箱 - 对接/api/user/email
  updateEmail: (data) => request.put('/user/email', data),

  // 实名认证 - 对接/api/user/verify-real-name
  verifyRealName: (data) => request.post('/user/verify-real-name', data)
};

// 地址管理API - 对接Spring Boot的/api/user/addresses
export const addressApi = {
  // 获取地址列表 - 对接/api/user/addresses
  getAddressList: () => request.get('/user/addresses'),

  // 添加地址 - 对接/api/user/addresses
  addAddress: (data) => request.post('/user/addresses', data),

  // 获取地址详情 - 对接/api/user/addresses/{id}
  getAddressDetail: (id) => request.get(`/user/addresses/${id}`),

  // 更新地址 - 对接/api/user/addresses/{id}
  updateAddress: (id, data) => request.put(`/user/addresses/${id}`, data),

  // 删除地址 - 对接/api/user/addresses/{id}
  deleteAddress: (id) => request.delete(`/user/addresses/${id}`),

  // 设置默认地址 - 对接/api/user/addresses/{id}/default
  setDefaultAddress: (id) => request.put(`/user/addresses/${id}/default`)
};

// 文件上传API - 对接Spring Boot的/api/upload
export const uploadApi = {
  // 上传单个文件 - 对接/api/upload
  uploadFile: (file, type = 'image') => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);

    return request.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 上传多个文件 - 对接/api/upload/multiple
  uploadFiles: (files, type = 'image') => {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    formData.append('type', type);

    return request.post('/upload/multiple', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
};

// 账户管理API - 对接Spring Boot的/api/account
export const accountApi = {
  // 获取账户余额 - 对接/api/account/balance
  getBalance: () => request.get('/account/balance'),

  // 充值 - 对接/api/account/recharge
  recharge: (data) => request.post('/account/recharge', data),

  // 提现 - 对接/api/account/withdraw
  withdraw: (data) => request.post('/account/withdraw', data),

  // 获取交易记录 - 对接/api/account/transactions
  getTransactions: (params) => request.get('/account/transactions', { params }),

  // 获取账户信息 - 对接/api/account/info
  getAccountInfo: () => request.get('/account/info')
};

// 积分管理API - 对接Spring Boot的/api/points
export const pointsApi = {
  // 获取积分余额 - 对接/api/points/balance
  getBalance: () => request.get('/points/balance'),

  // 获取积分记录 - 对接/api/points/records
  getRecords: (params) => request.get('/points/records', { params }),

  // 兑换积分 - 对接/api/points/exchange
  exchange: (data) => request.post('/points/exchange', data),

  // 获取积分规则 - 对接/api/points/rules
  getRules: () => request.get('/points/rules')
};

// 优惠券管理API - 对接Spring Boot的/api/coupons
export const couponApi = {
  // 获取优惠券列表 - 对接/api/coupons
  getCouponList: (params) => request.get('/coupons', { params }),

  // 获取可用优惠券 - 对接/api/coupons/available
  getAvailableCoupons: (params) => request.get('/coupons/available', { params }),

  // 领取优惠券 - 对接/api/coupons/{id}/claim
  claimCoupon: (id) => request.post(`/coupons/${id}/claim`),

  // 使用优惠券 - 对接/api/coupons/{id}/use
  useCoupon: (id, data) => request.post(`/coupons/${id}/use`, data),

  // 获取优惠券详情 - 对接/api/coupons/{id}
  getCouponDetail: (id) => request.get(`/coupons/${id}`)
};

// 收藏管理API - 对接Spring Boot的/api/favorites
export const favoriteApi = {
  // 获取收藏列表 - 对接/api/favorites
  getFavoriteList: (params) => request.get('/favorites', { params }),

  // 添加收藏 - 对接/api/favorites
  addFavorite: (type, targetId) => request.post('/favorites', { type, targetId }),

  // 取消收藏 - 对接/api/favorites/{id}
  removeFavorite: (id) => request.delete(`/favorites/${id}`),

  // 检查是否已收藏 - 对接/api/favorites/check
  checkFavorite: (type, targetId) => request.get('/favorites/check', { params: { type, targetId } })
};

// 帮助中心API - 对接Spring Boot的/api/help
export const helpApi = {
  // 获取帮助文章列表 - 对接/api/help/articles
  getArticleList: (params) => request.get('/help/articles', { params }),

  // 获取帮助文章详情 - 对接/api/help/articles/{id}
  getArticleDetail: (id) => request.get(`/help/articles/${id}`),

  // 获取常见问题 - 对接/api/help/faq
  getFAQ: (params) => request.get('/help/faq', { params }),

  // 提交反馈 - 对接/api/help/feedback
  submitFeedback: (data) => request.post('/help/feedback', data),

  // 联系客服 - 对接/api/help/contact
  contactSupport: (data) => request.post('/help/contact', data)
};

// 消息管理API - 对接Spring Boot的/api/messages
export const messageApi = {
  // 获取消息列表 - 对接/api/messages
  getMessageList: (params) => request.get('/messages', { params }),

  // 获取消息详情 - 对接/api/messages/{id}
  getMessageDetail: (id) => request.get(`/messages/${id}`),

  // 标记消息已读 - 对接/api/messages/{id}/read
  markAsRead: (id) => request.put(`/messages/${id}/read`),

  // 删除消息 - 对接/api/messages/{id}
  deleteMessage: (id) => request.delete(`/messages/${id}`),

  // 获取未读消息数量 - 对接/api/messages/unread-count
  getUnreadCount: () => request.get('/messages/unread-count'),

  // 获取未读消息数量（按类型分组）- 对接/api/messages/unread-counts
  getUnreadCounts: () => request.get('/messages/unread-counts'),

  // 获取消息统计 - 对接/api/messages/stats
  getMessageStats: () => request.get('/messages/stats'),

  // 发送消息 - 对接/api/messages
  sendMessage: (data) => request.post('/messages', data)
};

// 支付管理API - 对接Spring Boot的/api/payment
export const paymentApi = {
  // 创建支付订单 - 对接/api/payment/create
  createPayment: (data) => request.post('/payment/create', data),

  // 查询支付状态 - 对接/api/payment/{id}/status
  getPaymentStatus: (id) => request.get(`/payment/${id}/status`),

  // 支付回调处理 - 对接/api/payment/callback
  handleCallback: (data) => request.post('/payment/callback', data),

  // 获取支付方式 - 对接/api/payment/methods
  getPaymentMethods: () => request.get('/payment/methods'),

  // 退款申请 - 对接/api/payment/{id}/refund
  requestRefund: (id, data) => request.post(`/payment/${id}/refund`, data)
};

// 设置管理API - 对接Spring Boot的/api/settings
export const settingsApi = {
  // 获取用户设置 - 对接/api/settings
  getUserSettings: () => request.get('/settings'),

  // 更新用户设置 - 对接/api/settings
  updateUserSettings: (data) => request.put('/settings', data),

  // 获取隐私设置 - 对接/api/settings/privacy
  getPrivacySettings: () => request.get('/settings/privacy'),

  // 更新隐私设置 - 对接/api/settings/privacy
  updatePrivacySettings: (data) => request.put('/settings/privacy', data),

  // 获取通知设置 - 对接/api/settings/notifications
  getNotificationSettings: () => request.get('/settings/notifications'),

  // 更新通知设置 - 对接/api/settings/notifications
  updateNotificationSettings: (data) => request.put('/settings/notifications', data)
};

export default request;
